﻿using Com.Lancetinc.Evs.Controls;
using Com.Lancetinc.Evs.Events;
using Com.Lancetinc.Evs.Helpers;
using MaterialDesignThemes.Wpf;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Com.Lancetinc.Evs.Windows
{
    public partial class SettingControl : ISettingFlyoutControl
    {
        public SnackbarMessageQueue MessageQueue { get; } = new() { DiscardDuplicates = true };

        private readonly ISettingControl[] _settingControls;

        public SettingControl()
        {
            InitializeComponent();
            this.DataContext = this;
            _settingControls = new ISettingControl[] { CtrlDoctorSetting, CtrlReportTemplateSetting, CtrlPasswordManage };
            Init();
        }

        private void Init()
        {
            foreach (var ctrl in _settingControls)
            {
                ctrl.RequestClose += Ctrl_RequestClose;
                ctrl.RequestSave += Ctrl_RequestSave;
            }
        }

        private void Ctrl_RequestClose(object sender, EventArgs e)
        {
            this.Close();
        }
        private void Ctrl_RequestSave(object sender, EventArgs e)
        {
            this.Save();
        }

        private void Save()
        {
            var ctrls = _settingControls;
            bool saved = false;
            for (int i = 0; i < ctrls.Length; i++)
            {
                var ctrl = ctrls[i];
                if (!ctrl.CheckChanged())
                    continue;

                if (!ctrl.Save())
                {
                    TabMain.SelectedIndex = i;
                    return;
                }

                saved = true;
            }

            if (saved)
            {
                var msg = I18nHelper.Default.GetMessage("SettingWindow.SaveSuccess");
                MessageQueue.Enqueue(msg);
            }
        }

        private void Tab_Checked(object sender, RoutedEventArgs e)
        {
            if (!this.IsLoaded) return;

            var idxStr = (sender as FrameworkElement).Tag as string;
            var idx = int.Parse(idxStr);
            TabMain.SelectedIndex = idx;
        }

        private void Close()
        {
            (this.Parent as SettingFlyout)?.CloseFlyout();
        }

        /// <inheritdoc />
        public string Title => I18nHelper.Default.GetMessage("SettingWindow.Title");

        /// <inheritdoc />
        public bool IsPinned => true;

        /// <inheritdoc />
        public double WidthRequest => 500;

        /// <inheritdoc />
        public async Task<bool> ConfirmCloseAsync()
        {
            var ctrls = _settingControls;
            for (int i = 0; i < ctrls.Length; i++)
            {
                var ctrl = ctrls[i];
                if (!ctrl.CheckChanged())
                    continue;

                var ti = PanelTabs.Children[i] as RadioButton;
                var title = ti.Content.ToString();

                ti.IsChecked = true;
                var confirmMsg = I18nHelper.Default.GetMessageWithArgs("SettingWindow.ConfirmDiscardChange", title);
                var r = await MessageHelper.ShowYesNoAsync(confirmMsg);

                if (r != MessageBoxResult.Yes)
                {
                    return false;
                }
                // 仍然要关闭
                break;
            }

            return true;
        }

        private void TabMain_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_settingControls == null)
                return;

            bool showReportPreview = _settingControls[TabMain.SelectedIndex] is ReportTemplateSettingUserControl;
            KnownAppEvents.PublishReportTemplatePreviewChanged(showReportPreview);
        }
    }

    public interface ISettingControl
    {
        bool CheckChanged();

        bool Save();

        event EventHandler RequestClose;

        event EventHandler RequestSave;
    }
}
